package com.tgq.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tgq.demo.entity.Role;
import com.tgq.demo.entity.RoleMenu;
import com.tgq.demo.mapper.RoleMapper;
import com.tgq.demo.mapper.RoleMenuMapper;
import com.tgq.demo.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陶国庆
 * @since 2023-02-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Transactional //事物注解保证删除和保存都成功
    @Override
    public void setRoleMenu(Integer roleid, List<Integer> menuIds) {
//        第一种删除方法通过QueryWrapper
//        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("roid_id",roleId);
//        roleMenuMapper.delete(queryWrapper);

//        先删除当前角色id所有的绑定关系
//        第二种删除方法通过sql语句
          roleMenuMapper.deleteByRoleId(roleid);

//          再把前端传来的菜单id数组绑定到当前的这个角色id上去
        for (Integer menuId: menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRole_id(roleid);
            roleMenu.setMenu_id(menuId);
            roleMenuMapper.insert(roleMenu);

        }
    }

    @Override
    public List<Integer> getRoleMenuById(Integer roleId) {
        return roleMenuMapper.getRoleMenuById(roleId);
    }
}
